#include "ZFileOperate.h"

TZList *FindFiles(char *filepack,char *filestyle)
{
	TZList *filelst;
	filelst=new TZList(10);
	WIN32_FIND_DATAA FindFileData;
    HANDLE hFind = INVALID_HANDLE_VALUE;
    char DirSpec[MAX_PATH];  // directory specification
    DWORD dwError;
	char *tempname;
	int len;
	ZeroMemory(&FindFileData, sizeof(WIN32_FIND_DATAA));
    strncpy_s (DirSpec,MAX_PATH, filepack, strlen(filepack)+1);
    strncat_s (DirSpec,MAX_PATH, filestyle, strlen(filestyle));
    hFind = FindFirstFileA(DirSpec, &FindFileData);

    if (hFind == INVALID_HANDLE_VALUE) 
    {
		printf ("Invalid file handle. Error is %u\n", GetLastError());
		DelFileLst(filelst);
		return NULL;
    } 
    else 
    {
		len=strlen((char *)FindFileData.cFileName)+strlen(filepack)+1;
		tempname=new char[len+1];
		strncpy_s (tempname,len+1, filepack, strlen(filepack)+1);
		strncat_s(tempname,len+1, "\\",1);
		strncat_s (tempname,len+1, (char *)FindFileData.cFileName, strlen((char *)FindFileData.cFileName));
		filelst->add((LPVOID)tempname);
		while (FindNextFileA(hFind, &FindFileData) != 0) 
		{
			len=strlen((char *)FindFileData.cFileName)+strlen(filepack)+1;
			tempname=new char[len+1];
			strncpy_s (tempname,len+1, filepack, strlen(filepack)+1);
			strncat_s	(tempname,len+1, "\\",1);
			strncat_s (tempname,len+1 ,(char *)FindFileData.cFileName, strlen((char *)FindFileData.cFileName));
			filelst->add((LPVOID)tempname);
		}
    
		dwError = GetLastError();
		FindClose(hFind);
		if (dwError != ERROR_NO_MORE_FILES) 
		{
			printf ("FindNextFile error. Error is %u\n", dwError);
			DelFileLst(filelst);
			return NULL;
		}
	}
    return filelst;
}

void DelFileLst(TZList * filelst)
{
	int i;
	char *temp;
	if(filelst==NULL)
		return;
	for(i=filelst->count-1;i>=0;i--)
	{
		temp=(char *)filelst->items(i);
		delete []temp;
	}
	delete filelst;
}